﻿/// <reference path="jquery-bootgrid/dist/jquery.bootgrid.bykenny.js" />
/// <reference path="bootstrap3-dialog/js/bootstrap-dialog.min.js" />

; (function () {
    var exporter = window.BT || {};
    var ajaxDefaultOpt = {
        async: true,
        url: '',
        dataType: 'json',
        type: 'post'
    }

    var dialogDefaultBtnOpt = [{
        label: '取消',
        action: function (dialogItself) {
            dialogItself.close();
        }
    }, {
        label: '确认',
        cssClass: 'btn-primary',
        action: function () {

        }
    }];

    var confirmDefaultOpt = {
        title: '提示',
        message: '',
        type: BootstrapDialog.TYPE_WARNING,
        closable: true,
        draggable: true,
        btnCancelLabel: '取消',
        btnOKLabel: '确认',
        callback: function (result) {
        }
    };
    
    //var ChineseNumber= ['','一', '二', '三', '四', '五', '六', '七', '八', '九', '十', ]
    //dialog
    exporter.dialog = {};
    //消息框，传入消息
    exporter.dialog.info = function (msg) {
        alert(msg);
    }
    //消息框，传入消息
    exporter.dialog.warn = function (msg) {
        alert(msg);
    }
    //弹出框
    exporter.dialog.show = function (opt, sucessEvent) {
        var options = $.extend({}, opt);
        dialogDefaultBtnOpt[1]['action'] = sucessEvent;
        options['buttons'] = dialogDefaultBtnOpt;
        return BootstrapDialog.show(options);
    }
    //confirm框
    exporter.dialog.confirm = function (opt) {
        var options = $.extend({}, confirmDefaultOpt, opt);
        return BootstrapDialog.confirm(options);
    }
    //ajax
    exporter.ajax = function (opt, success, fail) {
        var ajaxOpt = $.extend({}, ajaxDefaultOpt, opt);
        success = success || (function (data) { });
        return $.ajax(ajaxOpt).done(success).fail(function () {
            fail && fail();
        });
    }
    //jq选择器是form表单选择器
    exporter.getSearchParam = function (jq) {
        var obj = {};
        var ck = $(':checkbox', jq);
        //todo 这里只考虑select是单选的情况
        //:text,:hidden,:checkbox,select
        $(':text,:hidden,select', jq).each(function (i, item) {
            var self = this;
            var me = $(self);
            if (me.val() || me.val == '0') {
                obj[self.name] = $.trim(me.val());
            }
        });
        ck.each(function (i, item) {
            var self = this;
            var me = $(self);
            //判断同名checkbox
            if ($('[name="' + self.name + '"]', ck).length > 1) {

            } else {

            }
        });
    }

    exporter.getChineseNumber = function () {

    }
    window.BT = exporter;

})();

/**绑定参数
*/
; (function () {
    $.fn.bindForm = function (params) {
        var me = this;
        return me.each(function () {
            var self = this;
            new FormBind({ 'form': $(self), 'params': params }).bind();
        });
    }
    function FormBind(opt) {
        this.form = opt.form;
        this.params = opt.params;
    }
    FormBind.prototype.bind = function () {
        var self = this;
        if (!self.params) return;
        $('input', self.form).each(function () {
            var me = this;
            if ($(me).attr('data-bind-ignore') == 'true') return true;//continue
            var val = self.timeFormatter(self.params[me.name]);
            //if (typeof val === 'object') return true;
            if (me.type == "text" || me.type == "hidden") {
                $(me).val(val);
            }
            else if (me.type == "checkbox") {
                if ($.isArray(val)) {
                    if ($.inArray($(me).val(), val) != -1) {
                        $(me).prop("checked", true);
                    }
                } else {
                    $(me).attr("checked", val == "True" || val == true);
                }
            }
            else if ((me.type == "radio")) {
                $("input[name=" + me.name + "][value=" + val + "]").prop("checked", true);
            }
        });
        //这里也只考虑SELECT单选的情况(多选要重写)
        $('textarea,select', self.form).each(function () {
            var val = self.params[this.name];
            if (val === null || val === undefined) return;
            $(this).val((self.params[this.name]));
        });
        //$('select', self.form).each(function () {
        //    var val = self.params[this.name];
        //    if (val === null) return;
        //    $(this).find("option[value='" +val.toString()+ "']").prop("selected", true);
        //});
        $('label', self.form).each(function () {
            var val = self.timeFormatter(self.params[$(this).attr("name")]);
            $(this).html(val);
        });
    }
    FormBind.prototype.timeFormatter = function (value) {
        if (value == null || value == "") return value;
        var date;
        if (value.toString().indexOf("\/Date(") == -1)
            return value;
        date = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var t = y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + ' ';
        var hh = date.getHours();
        var mm = date.getMinutes();
        var ss = date.getSeconds();
        if (ss === 0 && hh === 0 && mm == 0) return t;
        t += (hh < 10 ? ('0' + hh) : hh) + ':' + (mm < 10 ? ('0' + mm) : mm) + ':' + (ss < 10 ? ('0' + ss) : ss);
        return t;
    }
})();

/**获取查询参数
*/
; (function () {
    $.fn.serializeObject = function () {
        var o = {};
        var nameArray = [];
        var a = this.serializeArray();
        $.each(a, function () {
            //存在 name相同的情况
            var val = $.trim(this.value || '');
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                    nameArray.push(this.name);//防止重复(第一次才添加)
                }
                o[this.name].push(val);
   
            } else {
                o[this.name] = val;
            }
        });
        $.each(nameArray, function (i, item) {
            o[item] = o[item].join(',');
        });
        return o;
    };

})();

/**原型链扩展方法
*/
; (function () {
    /**string 扩展方法  字符串格式化
    */
    String.prototype.format = function (args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length == 1 && typeof (args) == "object") {
                for (var key in args) {
                    if (args[key] != undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }//example   var template2="我是{name}，今年{age}了";var result2=template2.format({name:"loogn",age:22});
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] != undefined) {
                        var reg = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }//expample var template1="我是{0}，今年{1}了"; var result1=template1.format("loogn",22);
            }
        }
        return result;
    }

    String.prototype.trim = function () {
        return $.trim(this);
    }

    String.prototype.trimEnd = function (str) {
        if (this.length == 0) return this;
        if (this.lastIndexOf(str) == this.length - 1) {
            return this.substr(0, this.length - 1);
        }
        return this;
    }

    String.prototype.toChineseNumber = function () {
        var k = new change(this);
        return k.pri_ary();
    }

    // 对Date的扩展，将 Date 转化为指定格式的String 
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
    // 例子： 
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
    Date.prototype.Format = function (fmt) { //author: meizz 
        var o = {
            "M+": this.getMonth() + 1,                 //月份 
            "d+": this.getDate(),                    //日 
            "h+": this.getHours(),                   //小时 
            "m+": this.getMinutes(),                 //分 
            "s+": this.getSeconds(),                 //秒 
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds()             //毫秒 
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }




    var _change = {
        ary0: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
        ary1: ["", "十", "百", "千"],
        ary2: ["", "万", "亿", "兆"],
        init: function (name) {
            this.name = name;
        },
        strrev: function () {
            var ary = []
            for (var i = this.name.length; i >= 0; i--) {
                ary.push(this.name[i])
            }
            return ary.join("");
        }, //倒转字符串。
        pri_ary: function () {
            var $this = this
            var ary = this.strrev();
            var zero = ""
            var newary = ""
            var i4 = -1
            for (var i = 0; i < ary.length; i++) {
                if (i % 4 == 0) { //首先判断万级单位，每隔四个字符就让万级单位数组索引号递增
                    i4++;
                    newary = this.ary2[i4] + newary; //将万级单位存入该字符的读法中去，它肯定是放在当前字符读法的末尾，所以首先将它叠加入$r中，
                    zero = ""; //在万级单位位置的“0”肯定是不用的读的，所以设置零的读法为空

                }
                //关于0的处理与判断。
                if (ary[i] == '0') { //如果读出的字符是“0”，执行如下判断这个“0”是否读作“零”
                    switch (i % 4) {
                        case 0:
                            break;
                            //如果位置索引能被4整除，表示它所处位置是万级单位位置，这个位置的0的读法在前面就已经设置好了，所以这里直接跳过
                        case 1:
                        case 2:
                        case 3:
                            if (ary[i - 1] != '0') {
                                zero = "零"
                            }
                            ; //如果不被4整除，那么都执行这段判断代码：如果它的下一位数字（针对当前字符串来说是上一个字符，因为之前执行了反转）也是0，那么跳过，否则读作“零”
                            break;

                    }

                    newary = zero + newary;
                    zero = '';
                }
                //如果不是“0”
                else { 
                    if (ary.length == 2 && i == 1 && (ary[1]=='1')) {
                        newary = this.ary1[i % 4]  + newary;
                    } else {
                        newary = this.ary0[parseInt(ary[i])] + this.ary1[i % 4] + newary; //就将该当字符转换成数值型,并作为数组ary0的索引号,以得到与之对应的中文读法，其后再跟上它的的一级单位（空、十、百还是千）最后再加上前面已存入的读法内容。
                    }
                }

            }
            if (newary.indexOf("零") == 0) {
                newary = newary.substr(1)
            }//处理前面的0
            return newary;
        }
    }

    //创建class类
    function change() {
        this.init.apply(this, arguments);
    }
    change.prototype = _change

    //创建实例
    //var k = new change("00102040");
    //alert(k.pri_ary())

})();


